﻿using CNative.WebApi.Utils;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Text;

namespace CNative.WebApi.Common
{
    public class ConfigSectionGroup<TConfigSection, TElement, TElementCollection> : System.Configuration.ConfigurationSectionGroup
        where TElement : ConfigurationElement, new()
        where TElementCollection : ElementCollection<TElement>
        where TConfigSection : ConfigSection<TElement, TElementCollection>
    {
        string elementName = "";
        public ConfigSectionGroup(string _elementName)
            : base()	// 忽略大小写
        {
            elementName = _elementName;
        }
        public ConfigSectionGroup()
            : base()	// 忽略大小写
        {
            elementName = typeof(TElement).Name;
        }
        public ConfigSection<TElement, TElementCollection> ConfigSection
        {
            get
            {
                return (ConfigSection<TElement, TElementCollection>)base.Sections[elementName];
            }
        }
    }

    public class ConfigSection<TElement, TElementCollection> : System.Configuration.ConfigurationSection
        where TElement : ConfigurationElement, new()
        where TElementCollection : ElementCollection<TElement>
    {
        private static readonly ConfigurationProperty s_property = new ConfigurationProperty(string.Empty, typeof(TElementCollection), null, ConfigurationPropertyOptions.IsDefaultCollection);

        [ConfigurationProperty("", Options = ConfigurationPropertyOptions.IsDefaultCollection)]
        public TElementCollection ElementCollection
        {
            get
            {
                return (TElementCollection)base[s_property];
            }
        }
        public string sectionsName = "MySections";
        public ConfigSection(string _sectionsName)
            : base()
        {
            sectionsName = _sectionsName;
        }
        public ConfigSection()
            : base()
        {
            sectionsName = typeof(TElement).Name + "Sections";
        }
        #region opt
        public static string ExecutablePath = "";
        static ConfigSection()
        {
            ExecutablePath = Assembly.GetEntryAssembly().Location;
        }
        /// <summary>
        /// 获取配置节对应集合
        /// </summary>
        /// <typeparam name="TElement"></typeparam>
        /// <param name="sectionName"></param>
        /// <param name="configPath"></param>
        /// <returns></returns>
        public List<TElement> GetElements(string sectionName = "", string configPath = "")
        {
            sectionName = string.IsNullOrEmpty(sectionName) ? this.sectionsName : sectionName;
           // ConfigurationManager.RefreshSection(sectionName);
            var config = ConfigurationManager.OpenExeConfiguration(string.IsNullOrEmpty(configPath) ? ExecutablePath : configPath);
            if (config == null)
                return null;
            var mySection = (ConfigSection<TElement, TElementCollection>)config.GetSection(sectionName);
            if (mySection == null)
                return null;
            return mySection.ElementCollection.Cast<TElement>().ToList();
        }
        /// <summary>
        /// 配置节更新
        /// </summary>
        /// <typeparam name="TElement"></typeparam>
        /// <typeparam name="TElementCollection"></typeparam>
        /// <param name="sce"></param>
        /// <param name="sectionName"></param>
        /// <param name="configPath"></param>
        public void UpdateElement(TElement sce, string sectionName = "", string configPath = "")
        {
            sectionName = string.IsNullOrEmpty(sectionName) ? this.sectionsName : sectionName;
            if (sce == null)
                return;
            var config = ConfigurationManager.OpenExeConfiguration(string.IsNullOrEmpty(configPath) ? ExecutablePath : configPath);
            if (config == null)
                return;
            var mySection = (ConfigSection<TElement, TElementCollection>)config.GetSection(sectionName);
            if (mySection == null)
                return;
            mySection.ElementCollection.Update(sce);
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection(sectionName);
        }
        /// <summary>
        /// 配置节是否存在
        /// </summary>
        /// <typeparam name="TElement"></typeparam>
        /// <typeparam name="TElementCollection"></typeparam>
        /// <param name="keyVal"></param>
        /// <param name="sectionName"></param>
        /// <param name="configPath"></param>
        /// <returns></returns>
        public bool ExistsElement(string keyVal, string sectionName = "", string configPath = "")
        {
            sectionName = string.IsNullOrEmpty(sectionName) ? this.sectionsName : sectionName;
            if (string.IsNullOrEmpty(keyVal))
                return false;
            var config = ConfigurationManager.OpenExeConfiguration(string.IsNullOrEmpty(configPath) ? ExecutablePath : configPath);
            if (config == null)
                return false;
            var mySection = (ConfigSection<TElement, TElementCollection>)config.GetSection(sectionName);
            if (mySection == null)
                return false;
            return mySection.ElementCollection.Exists(keyVal);
        }
        /// <summary>
        /// 配置节删除键值对
        /// </summary>
        /// <typeparam name="TElement"></typeparam>
        /// <typeparam name="TElementCollection"></typeparam>
        /// <param name="keyVal"></param>
        /// <param name="sectionName"></param>
        /// <param name="configPath"></param>
        public void DeleteElement(string keyVal, string sectionName = "", string configPath = "")
        {
            sectionName = string.IsNullOrEmpty(sectionName) ? this.sectionsName : sectionName;
            if (string.IsNullOrEmpty(keyVal))
                return;
            var config = ConfigurationManager.OpenExeConfiguration(string.IsNullOrEmpty(configPath) ? ExecutablePath : configPath);
            if (config == null)
                return;
            var mySection = (ConfigSection<TElement, TElementCollection>)config.GetSection(sectionName);
            if (mySection == null)
                return;
            mySection.ElementCollection.Delete(keyVal);
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }
        #endregion
    }

    //[ConfigurationCollection(typeof(TElement))]
    public class ElementCollection<TElement> : ConfigurationElementCollection
        where TElement : ConfigurationElement, new()
    {
        string elementName = "";
        string elementKey = "";
        public ElementCollection(string _elementName, string _elementKey="")
            : base(StringComparer.OrdinalIgnoreCase)	// 忽略大小写
        {
            elementName = _elementName;
            elementKey = _elementKey;
        }
        public ElementCollection()
            : base(StringComparer.OrdinalIgnoreCase)	// 忽略大小写
        {
            elementName = typeof(TElement).Name;
        }
        protected override object GetElementKey(ConfigurationElement element)
        {
            if(string.IsNullOrEmpty(elementKey))
                return elementName;
            return element.GetPropertyValue(elementKey);
        }

        protected override ConfigurationElement CreateNewElement()
        {
            return new TElement();
        }
        /// <summary>  
        /// 获取在派生的类中重写时用于标识配置文件中此元素集合的名称。  
        /// </summary>  
        /// <value>The name of the element.</value>  
        /// <returns>集合的名称；否则为空字符串。默认值为空字符串。</returns>  
        /// <remarks>Editor：v-liuhch CreateTime：2015/6/27 23:41:40</remarks>  
        protected override string ElementName
        {
            get
            {
                return elementName;
            }
        }
        /// <summary>  
        /// 获取集合中的元素数。  
        /// </summary>  
        /// <value>The count.</value>  
        /// <returns>集合中的元素数。</returns>  
        /// <remarks>Editor：v-liuhch CreateTime：2015/6/27 22:08:24</remarks>  
        public new int Count
        {
            get { return base.Count; }
        }
        /// <summary>  
        /// 获取或设置此配置元素的属性、特性或子元素。  
        /// </summary>  
        /// <param name="index">The index.</param>  
        /// <returns>ServiceCtrElement.</returns>  
        /// <remarks>Editor：v-liuhch</remarks> 
        public TElement this[int index]
        {
            get
            {
                return (TElement)base.BaseGet(index);
            }
            set
            {
                if (BaseGet(index) != null)
                {
                    BaseRemoveAt(index);
                }
                BaseAdd(index, value);
            }
        }
        /// <summary>
        /// 获取或设置此配置元素的属性、特性或子元素。  
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public new TElement this[string key]
        {
            get
            {
                return (TElement)base.BaseGet(key);
            }
        }
        public bool Exists(string key)
        {
            try
            {
                if (!string.IsNullOrEmpty(key))
                {
                    if (this[key.ToString()] != null)
                    {
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtil.Error(ex.TargetSite + "\n" + ex.StackTrace + "\n" + ex.Message);
            }
            return false;
        }
        public bool Exists(TElement element)
        {
            try
            {
                var key = GetElementKey(element);
                if (key != null)
                {
                    if (this[key.ToString()] != null)
                    {
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtil.Error(ex.TargetSite + "\n" + ex.StackTrace + "\n" + ex.Message);
            }
            return false;
        }
        public bool Update(TElement element)
        {
            try
            {
                var key = GetElementKey(element);
                if (key != null)
                {
                    if (this[key.ToString()] != null)
                    {
                        this.Remove(key.ToString());
                    }
                    this.Add(element);
                    return true;
                }
            }
            catch (Exception ex)
            {
                LogUtil.Error(ex.TargetSite + "\n" + ex.StackTrace + "\n" + ex.Message);
            }
            return false;
        }
        public bool Delete(string key)
        {
            try
            {
                if (!string.IsNullOrEmpty(key))
                {
                    if (this[key.ToString()] != null)
                    {
                        this.Remove(key.ToString());
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtil.Error(ex.TargetSite + "\n" + ex.StackTrace + "\n" + ex.Message);
            }
            return false;
        }
        public bool Delete(TElement element)
        {
            try
            {
                var key = GetElementKey(element);
                if (key != null)
                {
                    if (this[key.ToString()] != null)
                    {
                        this.Remove(key.ToString());
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtil.Error(ex.TargetSite + "\n" + ex.StackTrace + "\n" + ex.Message);
            }
            return false;
        }
        // 说明：如果不需要在代码中修改集合，可以不实现Add, Clear, Remove
        public void Add(TElement element)
        {
            this.BaseAdd(element);
        }
        public int IndexOf(TElement element)
        {

            return BaseIndexOf(element);
        }
        public void Remove(string name)
        {
            base.BaseRemove(name);
        }
        public void RemoveAt(int index)
        {
            BaseRemoveAt(index);
        }
        public void Clear()
        {
            BaseClear();
        }

    }
}
